<template>
  <div v-loading="loading" class="departments-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 用了一个行列布局 -->
        <TreeTools :tree-node="company" :is-root="true" @addDepts="addDepts" />
        <el-tree
          :default-expand-all="true"
          :data="departs"
          :props="defaultProps"
        >
          <TreeTools slot-scope="{data}" :tree-node="data" @delDepts="getDepartments" @addDepts="addDepts" @editDepts="editDepts" />
        </el-tree>
      </el-card>
      <!-- v-if 和 ref 不能一起使用 refs不是动态，需要等页面渲染完成后才能拿到DOM元素 -->
      <AddDept ref="addDept" :tree-node="node" :show-dialog.sync="showDialog" @addDepts="getDepartments" />
    </div>
  </div>
</template>

<script>
import TreeTools from './components/tree-tools.vue'
import AddDept from './components/add-dept.vue'
import { getDepartments } from '@/api/departments'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'Departments',
  components: {
    TreeTools,
    AddDept
  },
  data() {
    return {
      departs: [], // 首行以下全部部门数据
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      company: {}, // 首行数据
      showDialog: false, // 添加部门弹层
      node: {}, // 当前选中部门
      loading: false // 用来控制进度弹层的显示和隐藏
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
      this.loading = true
      const data = await getDepartments()
      this.company = { name: data.companyName, manager: data.companyManage || '负责人', id: '' }
      this.departs = tranListToTreeData(data.depts)
      this.loading = false
    },
    addDepts(node) {
      this.showDialog = true
      this.node = node
    },
    editDepts(node) {
      this.showDialog = true
      this.node = node
      this.$refs.addDept.getDepartDetail(node.id)
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
</style>
